'use strict'

import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
// import initIpcEvent from './main/modules/ipcEvent'
import { BASE_URL } from '@/main/config'

const isDevelopment = process.env.NODE_ENV !== 'production'

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let win: BrowserWindow
let newProjectWin: BrowserWindow
const newProjectWinURL = `${BASE_URL}/newProject`

async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1200,
    height: 900,
    title: process.platform === 'win32' ? '单片机驱动生成工具' : '',
    titleBarStyle: 'hiddenInset',
    frame: process.platform !== 'win32',
    show: true,
    hasShadow: process.platform !== 'darwin',
    webPreferences: {
      webSecurity: false,
      nodeIntegration: process.env
        .ELECTRON_NODE_INTEGRATION as unknown as boolean,
      contextIsolation: false,
      enableRemoteModule: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }
}

async function createNewProjectWindow() {
  newProjectWin = new BrowserWindow({
    parent: win,
    modal: true,
    show: false,
    webPreferences: {
      nodeIntegration: true
    }
  })
  newProjectWin.loadURL(newProjectWinURL)
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS3_DEVTOOLS)
  //   } catch (e: any) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  await createWindow()
  await createNewProjectWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

ipcMain.on('close-app', () => {
  if (win) {
    win.close()
  }
})
ipcMain.on('minisize-app', () => {
  win.minimize()
})
ipcMain.on('maxsize-app', () => {
  win.maximize()
})
ipcMain.on('restore-app', () => {
  win.restore()
})
ipcMain.on('open-newproject', () => {
  newProjectWin.show()
})
